package com.netease.nim.demo.main.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.netease.nim.demo.common.fragment.TFragment;
import com.netease.nim.demo.common.ui.viewpager.FadeInOutPageTransformer;
import com.netease.nim.demo.common.ui.viewpager.PagerSlidingTabStrip;
import com.netease.nim.demo.contact.cache.ContactDataCache;
import com.netease.nim.demo.main.adapter.MainTabPagerAdapter;
import com.netease.nim.demo.main.model.MainTab;
import com.netease.nim.demo.main.reminder.ReminderItem;
import com.netease.nim.demo.main.reminder.ReminderManager;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.SystemMessageObserver;
import com.netease.nimlib.sdk.msg.SystemMessageService;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.shwread.android.qysw.activity.NewInteractionCreateTeamChMActivity;
import com.shwread.android.qysw10000227.R;

import logic.constants.Const;
import logic.constants.DefaultConsts;


/**
 * 云信主界面（导航页）
 */
public class HomeFragment
        extends
        TFragment
        implements
        OnPageChangeListener,
        ReminderManager.UnreadNumChangedCallback
{
	
	OnClickListener l = new OnClickListener()
	                  {

		                  @Override
		                  public void onClick(View v) {
			                  switch (v.getId()) {
								  case R.id.common_header_back:
									  getActivity().onBackPressed();
									  break;
								  case R.id.common_header_publish:
									  Intent creatTeamIntent = new Intent(getActivity(), NewInteractionCreateTeamChMActivity.class);
									  creatTeamIntent.putExtra(DefaultConsts.NI_CONTACT_INTENT, DefaultConsts.NI_CONTACT_CREATE_TEAM);
									  startActivityForResult(creatTeamIntent, MainTabFragment.CREATE_TEAM);
									  break;
								  default:
									  break;
							  }
						  }
	                  };
	private PagerSlidingTabStrip tabs;
	private ViewPager            pager;
	private int                  scrollState;
	private MainTabPagerAdapter  adapter;
	private View                 rootView;
	private Button               backBtn;
	private TextView             titleTView;
	private Button               createTeamBtn;
	private Observer<Integer> sysMsgUnreadCountChangedObserver = new Observer<Integer>()
	                                                           {
		                                                           @Override
		                                                           public void onEvent(Integer unreadCount) {
			                                                           ContactDataCache.getInstance().setSysMsgUnreadCount(unreadCount);
			                                                           ReminderManager.getInstance().updateContactUnreadNum(unreadCount);
		                                                           }
	                                                           };
	
	public HomeFragment() {
		setFragmentId(R.id.welcome_container);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		rootView = inflater.inflate(R.layout.netease_main, container, false);
		return rootView;
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		findViews();
		setupPager();
		setupTabs();
		registerMsgUnreadInfoObserver(true);
		registerSystemMessageObservers(true);
		requestSystemMessageUnreadCount();
	}
	
	@Override
	public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
		// TO TABS
		tabs.onPageScrolled(position, positionOffset, positionOffsetPixels);
		// TO ADAPTER
		adapter.onPageScrolled(position);
	}
	
	@Override
	public void onPageSelected(int position) {
		// TO TABS
		tabs.onPageSelected(position);

		selectPage(position);

		enableMsgNotification(false);
	}
	
	@Override
	public void onPageScrollStateChanged(int state) {
		// TO TABS
		tabs.onPageScrollStateChanged(state);

		scrollState = state;

		selectPage(pager.getCurrentItem());
	}
	
	private void selectPage(int page) {
		// TO PAGE
		if (scrollState == ViewPager.SCROLL_STATE_IDLE)
		{
			adapter.onPageSelected(pager.getCurrentItem());
		}
	}
	
	public void switchTab(int tabIndex, String params) {
		pager.setCurrentItem(tabIndex);
	}
	
	/**
	 * 查找页面控件
	 */
	private void findViews() {
		initTitle();
		tabs = (PagerSlidingTabStrip) getView().findViewById(R.id.tabs);
		pager = (ViewPager) getView().findViewById(R.id.main_tab_pager);
	}
	
	void initTitle() {
		backBtn = (Button) getView().findViewById(R.id.common_header_back);
		backBtn.setVisibility(View.VISIBLE);
		titleTView = (TextView) getView().findViewById(R.id.common_header_name);
		titleTView.setVisibility(View.VISIBLE);
		titleTView.setText(getString(R.string.session_contact));
		createTeamBtn = (Button) getView().findViewById(R.id.common_header_publish);
		if (Const.UserRole.equals("1"))
		{
			createTeamBtn.setVisibility(View.VISIBLE);
		}
		else
		{
			createTeamBtn.setVisibility(View.GONE);
		}
		createTeamBtn.setText("建群");
		backBtn.setOnClickListener(l);
		createTeamBtn.setOnClickListener(l);
	}
	
	@Override
	public void onResume() {
		super.onResume();
		enableMsgNotification(false);
		//quitOtherActivities();
	}
	
	@Override
	public void onPause() {
		super.onPause();
		enableMsgNotification(true);
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		registerMsgUnreadInfoObserver(false);
		registerSystemMessageObservers(false);
	}
	
	public boolean onBackPressed() {
		return false;
	}
	
	public boolean onClick(View v) {
		return true;
	}
	
	/**
	 * 设置viewPager
	 */
	private void setupPager() {
		// CACHE COUNT
		adapter = new MainTabPagerAdapter(getFragmentManager(), getActivity(), pager);
		pager.setOffscreenPageLimit(adapter.getCacheCount());
		// page swtich animation
		pager.setPageTransformer(true, new FadeInOutPageTransformer());
		// ADAPTER
		pager.setAdapter(adapter);
		// TAKE OVER CHANGE
		pager.setOnPageChangeListener(this);
	}
	
	/**
	 * 设置tab条目
	 */
	private void setupTabs() {
		tabs.setOnCustomTabListener(new PagerSlidingTabStrip.OnCustomTabListener()
		{
			@Override
			public int getTabLayoutResId(int position) {
				return R.layout.tab_layout_main;
			}

			@Override
			public boolean screenAdaptation() {
				return true;
			}
		});
		tabs.setViewPager(pager);
		tabs.setOnTabClickListener(adapter);
		tabs.setOnTabDoubleTapListener(adapter);
	}
	
	private void enableMsgNotification(boolean enable) {
		boolean msg = (pager.getCurrentItem() != MainTab.RECENT_CONTACTS.tabIndex);
		if (enable | msg)
		{
			NIMClient.getService(MsgService.class).setChattingAccount(MsgService.MSG_CHATTING_ACCOUNT_NONE, SessionTypeEnum.None);
		}
		else
		{
			NIMClient.getService(MsgService.class).setChattingAccount(MsgService.MSG_CHATTING_ACCOUNT_ALL, SessionTypeEnum.None);
		}
	}
	
	/**
	 * 未读消息数量观察者
	 */

	private void registerMsgUnreadInfoObserver(boolean register) {
		if (register)
		{
			ReminderManager.getInstance().registerUnreadNumChangedCallback(this);
		}
		else
		{
			ReminderManager.getInstance().unregisterUnreadNumChangedCallback(this);
		}
	}
	
	@Override
	public void onUnreadNumChanged(ReminderItem item) {
		MainTab tab = MainTab.fromReminderId(item.getId());
		if (tab != null)
		{
			tabs.updateTab(tab.tabIndex, item);
		}
	}
	
	/**
	 * 注册/注销系统消息未读数变化
	 *
	 * @param register
	 */
	private void registerSystemMessageObservers(boolean register) {
		NIMClient.getService(SystemMessageObserver.class).observeUnreadCountChange(sysMsgUnreadCountChangedObserver, register);
	}
	
	private void requestSystemMessageUnreadCount() {
		NIMClient.getService(SystemMessageService.class).querySystemMessageUnreadCount().setCallback(new RequestCallback<Integer>()
		{
			@Override
			public void onSuccess(Integer unreadCount) {
				ContactDataCache.getInstance().setSysMsgUnreadCount(unreadCount);
				ReminderManager.getInstance().updateContactUnreadNum(unreadCount);
			}
			
			@Override
			public void onFailed(int code) {
				
			}
			
			@Override
			public void onException(Throwable exception) {
				
			}
		});
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		for (int i = 0; i < adapter.getCount(); i++)
		{
			adapter.fragments[i].onActivityResult(requestCode, resultCode, data);
		}
		//		adapter.fragments[adapter.lastPostion].onActivityResult(requestCode, resultCode, data);
		
	}
}
